<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="维修单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入维修单号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="模具" prop="accountId">
        <el-select @change="handleQuery" clearable class="!w-240px" v-model="queryParams.accountId" placeholder="请选择模具"
          check-strictly filterable>
          <el-option v-for="dict in accountList" :key="dict.id" :label="dict.code" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="故障分类" prop="faultId">
        <el-select v-model="queryParams.faultId" placeholder="请选择故障分类" clearable class="!w-240px">
          <el-option v-for="cat in repaircategories" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请人" prop="applicantId">
        <el-select v-model="queryParams.applicantId" placeholder="请选择申请人" clearable class="!w-240px">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请部门" prop="departId">
        <el-tree-select v-model="queryParams.departId" :data="deptTree" :props="defaultProps" check-strictly filterable
          clearable default-expand-all placeholder="请选择申请部门" value-key="id" class="!w-240px" />
      </el-form-item>

      <el-form-item label="紧急程度" prop="urgencyLevel">
        <el-select v-model="queryParams.urgencyLevel" placeholder="请选择紧急程度" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_REPAIR_URGENCY_LEVEL)" :key="dict.value"
            :label="dict.label" :value="dict.value" /> </el-select>
      </el-form-item>

      <el-form-item label="维修状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_REPAIR_STATUS)" :key="dict.value"
            :label="dict.label" :value="dict.value" /> </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mold:repair-account:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mold:repair-account:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['mold:repair-account:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange" border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="维修单号" align="center" prop="code" />
      <el-table-column label="模具名称" align="center" prop="accountName" />
      <el-table-column label="模具编码" align="center" prop="accountCode" />
      <el-table-column label="故障分类" align="center" prop="faultName" />
      <el-table-column label="申请人" align="center" prop="applicantName" />
      <el-table-column label="申请部门" align="center" prop="departName" />
      <el-table-column label="紧急程度" align="center" prop="urgencyLevel">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_REPAIR_URGENCY_LEVEL" :value="scope.row.urgencyLevel" />
        </template>
      </el-table-column>
      <el-table-column label="故障时间" align="center" prop="faultTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="申请时间" align="center" prop="applicationTime" :formatter="dateFormatter" width="180px" />

      <el-table-column label="故障描述" align="center" prop="faultDescription" width="120">
        <template #default="scope">
          <div class="rich-text-content" v-html="scope.row.faultDescription"></div>
        </template>
      </el-table-column>

      <el-table-column label="维修方式" align="center" prop="repairMethod">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_REPAIR_METHOD" :value="scope.row.urgencyLevel" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_REPAIR_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="160px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['mold:repair-account:update']" v-if="scope.row.status === 1">
            编辑
          </el-button>
          <el-button link type="primary" @click="handleDispatch(scope.row.id)" v-if="scope.row.status === 1">
            派工
          </el-button>
          <el-button link type="primary" @click="handleCancelDispatch(scope.row.id)" v-if="scope.row.status === 2">
            撤销
          </el-button>
          <el-button link type="primary" @click="handleAudit(scope.row)" v-if="scope.row.status === 4">
            审核
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mold:repair-account:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RepairAccountForm ref="formRef" @success="getList" />

  <!-- 派工弹窗 -->
  <RepairAccountDispatch ref="dispatchFormRef" @success="getList" />

  <!-- 审核 -->
  <RepairAccountAudit ref="auditFormRef" @success="getList" />

</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'
import download from '@/utils/download'
import { RepairAccountApi, RepairAccount } from '@/api/mold/repairaccount'
import RepairAccountForm from './RepairAccountForm.vue'
import { AccountApi } from '@/api/mold/account'
import { RepairFaultCategoryApi } from '@/api/mold/repairfaultcategory'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import RepairAccountDispatch from './RepairAccountDispatch.vue'
import RepairAccountAudit from './RepairAccountAudit.vue'

/** 模具维修申请 列表 */
defineOptions({ name: 'RepairAccount' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<RepairAccount[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  accountId: undefined,
  faultId: undefined,
  applicantId: undefined,
  departId: undefined,
  urgencyLevel: undefined,
  faultTime: [],
  applicationTime: [],
  faultDescription: undefined,
  repairMethod: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const accountList = ref([])
const repaircategories = ref()
const userList = ref<UserVO[]>([])
const deptTree = ref() // 树形结构

/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  let parentId = 115
  const data = await DeptApi.getDeptsById(parentId)
  let dept: Tree = { id: parentId, name: '阿能集团', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

const getRepaircategories = async () => {
  repaircategories.value = []
  const data = await RepairFaultCategoryApi.getRepairFaultCategoryAll()
  repaircategories.value = handleTree(data)
}

const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RepairAccountApi.getRepairAccountPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const dispatchFormRef = ref()
/** 派工按钮操作 */
const handleDispatch = async (id: number) => {
  dispatchFormRef.value.open(id)
  handleQuery()
}

/** 撤销按钮操作 */
const handleCancelDispatch = async (id: number) => {
  message.confirm('确认要撤销此任务,同时删除该设备保养任务吗？').then(async () => {
    await RepairAccountApi.cancelDispatchRepairAccount(id).then(() => {
      message.success('撤销成功')
    }).finally(() => {
      handleQuery()
    })
  })
}

const auditFormRef = ref()

/** 审核按钮操作 */
const handleAudit = async (row: RepairAccount) => {
  console.log('row', row)
  auditFormRef.value.open(row.id, row.jobId)
  handleQuery()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RepairAccountApi.deleteRepairAccount(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除模具维修申请 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RepairAccountApi.deleteRepairAccountList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RepairAccount[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RepairAccountApi.exportRepairAccount(queryParams)
    download.excel(data, '模具维修申请.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getTree()
  getList()
  getAccountList()
  getRepaircategories()
  getUserList()
})
</script>